import axios from 'axios';
import { ElMessage } from 'element-plus';
import { showLoading,hideLoading } from './loading'
import Cookies from 'js-cookie'
import router from '@/router/index'
export default {
  install: function (Vue) {
    axios.defaults.timeout = 300000;
    // if(process.env.NODE_ENV==='production'){
    //   axios.defaults.baseURL = ''
    // }
    // 配置发送请求的信息
    axios.interceptors.request.use(config => {
      const token = Cookies.get('MicroCarLoan_Authorization')
      if (token) {
        config.headers['Authorization'] = token;
      }
      showLoading()
      return config;
    }, function (error) {
      return Promise.reject(error);
    });
    //配置请求回来的信息
    axios.interceptors.response.use( response => {
      hideLoading()
      switch (response.status) {
        case 200:
          if(response.data.code==500){
            ElMessage.error(response.data.message)
            return
          }
          if(response.data.code==401){
            router.push({name:'login'});
            return
          }
          break;
      }
      return response.data;
    }, function (error) {
        hideLoading()
      try {
        switch (error.response.status) {
          case 400:
            ElMessage.error('服务器内部错误')
            break;
          case 401:
            // ElMessage.error('登录状态失效')
            router.push({name:'login'});
            break;
          case 403:
            ElMessage.error(error.response.data.message)
            break;
          case 404:
            ElMessage.error('请求地址错误')
            break;
          case 500:
            break;
          case 502:
            break;
          case 504:
            break;
          default:
            ElMessage.error('服务器内部错误')
            break;
        }
      } catch (e) {
      }
      return Promise.reject(error);
    });
  }
}
